package com.yehongyu.mytools.basic.util.datetime;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtils {

    public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    // 获取当前系统时间戳Timestamp
    public static Timestamp getSysTimestamp() {
        return new Timestamp((new java.util.Date()).getTime());
    }

    /**
     * 根据字符串生成时间
     *
     * @param datetime
     * @return
     */
    public static Timestamp getstrTimestamp(String datetime) {
        Date bb = null;
        try {
            bb = DateFormat.getDateInstance().parse(datetime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (bb != null) {
            return new Timestamp(bb.getTime());
        } else {
            return null;
        }
    }

    /**
     *
     * @param datetime
     * @param datepattern
     * @return
     */
    public static Timestamp getstrTimestamp(String datetime, String datepattern) {
        java.util.Date bb = null;

        try {
            DateFormat parser = new SimpleDateFormat(datepattern);
            bb = parser.parse(datetime);
            return new Timestamp(bb.getTime());
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return null;

    }

    /**
     *
     * @param strMon
     * @return
     */
    public static String getCurMonBegin(String strMon) {
        String bdate = "";
        bdate = strMon + "-01";
        return bdate;
    }

    /**
     *
     * @param strMon
     * @return
     */
    public static String getCurMonEnd(String strMon) {
        String bdate = "";
        bdate = addDate(addDate(strMon + "-01", "M", 1), "D", -1);
        return bdate;
    }

    /**
     *
     * @param strDate
     * @return
     */
    public static String getCurWeekBegin(String strDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.parse(strDate, new ParsePosition(0));
        Calendar calendar = dateFormat.getCalendar();
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        calendar.add(Calendar.DATE, 1 - day);
        return dateFormat.format(calendar.getTime());
    }

    /**
     *
     * @param strDate
     * @return
     */
    public static String getCurWeekEnd(String strDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.parse(strDate, new ParsePosition(0));
        Calendar calendar = dateFormat.getCalendar();
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        calendar.add(Calendar.DATE, 7 - day);
        return dateFormat.format(calendar.getTime());
    }

    /**
     *
     * @param date
     * @param edate
     * @return
     */
    public static boolean comDate(String date, String edate) {
        //
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date dt1 = formatter.parse(date, new ParsePosition(0));
        java.util.Date dt2 = formatter.parse(edate, new ParsePosition(0));
        return (!dt1.before(dt2));

		/*
		 * if (date.compareTo(edate) == -1) { return false; } else { return
		 * true; }
		 */

    }

    /**
     *
     * @param date
     * @param type
     * @param into
     * @return
     */
    public static String addDateTime(String date, String type, int into) {
        date = date.replaceAll("-", "/");
        GregorianCalendar grc = new GregorianCalendar();
        grc.setTime(getstrTimestamp(date));
        if (type.equals("D")) {
            grc.add(GregorianCalendar.DATE, into);
        } else if (type.equals("M")) {
            grc.add(GregorianCalendar.MONTH, into);
        } else if (type.equals("Y")) {
            grc.add(GregorianCalendar.YEAR, into);
        } else if (type.equals("HH")) {
            grc.add(GregorianCalendar.HOUR, into);
        } else if (type.equals("MI")) {
            grc.add(GregorianCalendar.MINUTE, into);
        } else if (type.equals("SS")) {
            grc.add(GregorianCalendar.SECOND, into);
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String Sdate = new String(formatter.format(grc.getTime()));
        return Sdate;
    }

    /**
     *
     * @param date
     * @param type
     * @param into
     * @return
     */
    public static Timestamp addDateTime(Timestamp date, String type, int into) {
        GregorianCalendar grc = new GregorianCalendar();
        grc.setTime(new java.util.Date(date.getTime()));
        if (type.equals("D")) {
            grc.add(GregorianCalendar.DATE, into);
        } else if (type.equals("M")) {
            grc.add(GregorianCalendar.MONTH, into);
        } else if (type.equals("Y")) {
            grc.add(GregorianCalendar.YEAR, into);
        } else if (type.equals("HH")) {
            grc.add(GregorianCalendar.HOUR, into);
        } else if (type.equals("MI")) {
            grc.add(GregorianCalendar.MINUTE, into);
        } else if (type.equals("SS")) {
            grc.add(GregorianCalendar.SECOND, into);
        }
        return new Timestamp(
                new java.util.Date(grc.getTimeInMillis()).getTime());
    }

    /**
     *
     * @param date
     * @param type
     * @param into
     * @return
     */
    public static String addDate(String date, String type, int into) {
        // java.util.Date jj = new java.util.Date();
        // String date_temp = DateChange.getSysENDate();
        // (jj.getYear() + 1900) + "/" + (jj.getMonth() + 1) + "/"
        // +jj.getDate();
        // System.out.println(date);
        // date = eims3.hc360.media.resouce.Replacestr.Replace(date, "-", "/");
        GregorianCalendar grc = new GregorianCalendar();
        grc.setTime(getstrTimestamp(date));
        if (type.equals("D")) {
            grc.add(GregorianCalendar.DATE, into);
        } else if (type.equals("M")) {
            grc.add(GregorianCalendar.MONTH, into);
        } else if (type.equals("Y")) {
            grc.add(GregorianCalendar.YEAR, into);
        } else {
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        String Sdate = new String(formatter.format(grc.getTime()));

        // DateFormat dateFormat =
        // DateFormat.getDateInstance(DateFormat.MEDIUM);
        return Sdate;
    }

    /**
     *
     * @param date
     * @return
     */
    public static String getDateString(String date) {
        date = date.substring(0, 10);
        // date.indexOf()
        return date;
    }

    /**
     *
     * @param date
     * @return
     */
    public static String getDateString(Timestamp date) {
        if (date == null)
            return null;
        String s = date.toString();
        return s.substring(0, 10);
    }

    /**
     *
     * @param exifDate
     * @return
     */
    public static Date parseDate(String exifDate) {
        if (exifDate == null) {
            return null;
        }
        String patterns[];
        int i;
        patterns = (new String[] { "yyyy:MM:dd HH:mm:ss", "yyyy:MM:dd HH:mm",
                "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "dd.MM.yy HH:mm",
                "yyyyMMdd HHmmss", "yyyyMMdd HHmm", "MM/dd/yy hh:mm a",
                "HH:mm:ss dd.MM.yyyy", "yyyy:MM:dd", "yyyy-MM-dd", "dd.MM.yy",
                "yyyyMMdd", "MM/dd/yy", "yyyy:MM:dd HH:mm:sss", "yyyy/MM/dd" });
        for (i = 0; i < patterns.length; i++) {
            try {
                DateFormat parser = new SimpleDateFormat(patterns[i]);
                return parser.parse(exifDate);
            } catch (ParseException ex) {
            }
        }
        return null;
    }

    /**
     *
     * @param date
     * @param pattern
     * @return
     */
    public static Date parseDate(String date, String pattern) {
        if (date == null)
            return null;

        try {
            DateFormat parser = new SimpleDateFormat(pattern);
            return parser.parse(date);
        } catch (ParseException ex) {
        }

        return null;
    }

    /**
     *
     * @param timestamp
     * @param pattern
     * @return
     */
    public static String parseDate(Timestamp timestamp, String pattern) {
        if (timestamp == null)
            return null;

        DateFormat parser = new SimpleDateFormat(pattern);
        return parser.format(timestamp);
    }

    /**
     *
     * @param time1
     * @param time2
     * @return
     */
    public static int getDiscrepancyNum(Timestamp time1, Timestamp time2) {
        int result = 0;
        if (time1 != null && time2 != null) {
            long temp = time1.getTime() - time2.getTime();
            if (temp > 0) {
                result = (int) ((temp / (24 * 60 * 60 * 1000)));
            } else {
                result = -(int) (((temp / (24 * 60 * 60 * 1000))));
            }

        }
        return result;
    }

    /**
     *
     * @param unit
     * @param testDate
     * @param refDate
     * @return
     * @throws IllegalArgumentException
     */
    public static int dateDiff(char unit, Date testDate, Date refDate)
            throws IllegalArgumentException {
        long testDateMillis = testDate.getTime();
        long refDateMillis = refDate.getTime();
        unit = Character.toUpperCase(unit);
        if (unit != 'D') {
            throw new IllegalArgumentException(
                    "锟斤拷效锟侥碉拷位锟斤拷锟斤拷前只锟斤拷锟斤拷锟?? 'D' (锟斤拷锟斤拷) 锟侥硷拷锟斤拷!");
        } else {
            return (int) ((testDateMillis - refDateMillis) / 1000L / 60L / 60L / 24L);
        }
		/* @todo,锟斤拷锟揭拷锟斤拷锟斤拷锟斤拷锟叫达拷锟斤拷锟斤拷锟?? */
    }

    /**
     *
     * @param unit
     * @param testDate
     * @param refDate
     * @return
     * @throws IllegalArgumentException
     */
    public static int dateDiff(char unit, String testDate, String refDate)
            throws IllegalArgumentException {
        return dateDiff(unit, toDate(testDate), toDate(refDate));
    }

    public static Date toDate(String dateString) {
        return parseDate(dateString);
    }

    public static void main(String[] args) {

        int i = dateDiff('D', "2005-02-01", "2005-02-03");
        System.out.println("i=" + i);
    }

    private static final String DEF_DATE_FORMAT = "yyyy/MM/dd";

    private static final String DEF_TIME_FORMAT = "HH:mm:ss";

    public static String getDateString(Date d) {
        return getString(d, DEF_DATE_FORMAT);
    }

    public static String getTimeString(Date d) {
        return getString(d, DEF_TIME_FORMAT);
    }

    public static String getString(Date d, String pattern) {
        String ret;
        try {
            ret = new SimpleDateFormat(pattern).format(d);
        } catch (Exception e) {
            ret = null;
        }
        return ret;
    }

}
